package com.houweishi.module.record.service.impl;

import com.alibaba.fastjson.JSON;
import com.houweishi.common.constant.Constants;
import com.houweishi.common.constant.HttpStatus;
import com.houweishi.common.core.domain.AjaxResult;
import com.houweishi.common.core.domain.entity.SysDept;
import com.houweishi.common.core.domain.entity.SysUser;
import com.houweishi.common.core.domain.model.LoginUser;
import com.houweishi.common.exception.base.BaseException;
import com.houweishi.common.utils.DateUtils;
import com.houweishi.common.utils.SecurityUtils;
import com.houweishi.common.utils.StringUtils;
import com.houweishi.module.oaEntry.service.IOaEntryService;
import com.houweishi.module.purchase.domain.OaPurchase;
import com.houweishi.module.purchase.domain.OaPurchaseProduct;
import com.houweishi.module.purchase.mapper.OaPurchaseMapper;
import com.houweishi.module.purchase.mapper.OaPurchaseProductMapper;
import com.houweishi.module.receipt.domain.BizReceipt;
import com.houweishi.module.receipt.domain.BizReceiptProduct;
import com.houweishi.module.receipt.mapper.BizReceiptMapper;
import com.houweishi.module.receipt.mapper.BizReceiptProductMapper;
import com.houweishi.module.record.domain.BizApprovalRecord;
import com.houweishi.module.record.mapper.BizApprovalRecordMapper;
import com.houweishi.module.record.service.IBizApprovalRecordService;
import com.houweishi.module.syTableRecord.service.ISyTableRecordTService;
import com.houweishi.system.mapper.SysUserMapper;
import com.houweishi.system.service.ISysDeptService;
import com.houweishi.ws.po.Message;
import com.houweishi.ws.service.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 审批信息记录Service业务层处理
 *
 * @author houweishi
 * @date 2023-02-21
 */
@Service
public class BizApprovalRecordServiceImpl implements IBizApprovalRecordService {
    private static final Logger LOGGER = LoggerFactory.getLogger(BizApprovalRecordServiceImpl.class);
    @Resource
    private BizApprovalRecordMapper bizApprovalRecordMapper;
    @Resource
    private OaPurchaseMapper oaPurchaseMapper;
    @Resource
    private OaPurchaseProductMapper oaPurchaseProductMapper;
    @Resource
    private BizReceiptMapper bizReceiptMapper;
    @Resource
    private BizReceiptProductMapper bizReceiptProductMapper;

    @Resource
    private ISysDeptService iSysDeptService;

    /**
     * 用户Mapper
     */
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 记录表Service
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;


    /**
     * 消息提示
     */
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 入职申请
     */
    @Resource
    private IOaEntryService iOaEntryService;

    /**
     * 查询审批信息记录
     *
     * @param id 审批信息记录主键
     * @return 审批信息记录
     */
    @Override
    public BizApprovalRecord selectBizApprovalRecordById(Long id) {
        return bizApprovalRecordMapper.selectBizApprovalRecordById(id);
    }

    /**
     * 查询审批信息记录列表
     *
     * @param bizApprovalRecord 审批信息记录
     * @return 审批信息记录
     */
    @Override
    public List<BizApprovalRecord> selectBizApprovalRecordList(BizApprovalRecord bizApprovalRecord) {
        return bizApprovalRecordMapper.selectBizApprovalRecordList(bizApprovalRecord);
    }

    /**
     * 新增审批信息记录
     *
     * @param bizApprovalRecord 审批信息记录
     * @return 结果
     */
    @Override
    public int insertBizApprovalRecord(BizApprovalRecord bizApprovalRecord) {
        return bizApprovalRecordMapper.insertBizApprovalRecord(bizApprovalRecord);
    }

    /**
     * 修改批信息记录
     *
     * @param bizApprovalRecord 审批信息记录
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateBizApprovalRecord(BizApprovalRecord bizApprovalRecord) {
        // 校验是否登录
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return new AjaxResult(HttpStatus.UNAUTHORIZED, "请先登录");
        }
        List<BizApprovalRecord> currApprovalRecords = null;
        // 获取当前审批记录：根据流水单号，审批状态，审批人获取审批信息
        if (!Constants.RECALL.equals(bizApprovalRecord.getTypeOperation())) {
            currApprovalRecords = bizApprovalRecordMapper.selectBizApprovalRecordList(new BizApprovalRecord(loginUser.getUserId(), Constants.APPROVE, bizApprovalRecord.getSerialNum()));
            if (CollectionUtils.isEmpty(currApprovalRecords)) {
                return new AjaxResult(HttpStatus.ERROR, "您不是当前审批人或该审批记录异常");
            }
        }
        // 操作同意
        if (Constants.AGREE.equals(bizApprovalRecord.getTypeOperation())) {
            // 操作同意
            agreeApprovalRecord(bizApprovalRecord, loginUser, currApprovalRecords);
        } else if (Constants.REJECTED.equals(bizApprovalRecord.getTypeOperation())) {
            // 操作驳回
            rejectedApprovalRecord(bizApprovalRecord, loginUser, currApprovalRecords);
        } else if (Constants.DEFERRED.equals(bizApprovalRecord.getTypeOperation())) {
            // 延迟操作
            deferredApprovalRecord(bizApprovalRecord, loginUser, currApprovalRecords);
        } else if (Constants.RECALL.equals(bizApprovalRecord.getTypeOperation())) {
            AjaxResult recallResult = recallApprovalRecord(bizApprovalRecord, loginUser);
            if (recallResult != null) {
                return recallResult;
            }
        } else {
            return new AjaxResult(HttpStatus.ERROR, "操作类型不匹配");
        }
        return new AjaxResult(HttpStatus.SUCCESS, "操作成功");
    }

    /**
     * 延迟操作
     *
     * @param bizApprovalRecord
     * @param loginUser
     * @param currApprovalRecords
     */
    @Transactional(rollbackFor = Exception.class)
    public void deferredApprovalRecord(BizApprovalRecord bizApprovalRecord, LoginUser loginUser, List<BizApprovalRecord> currApprovalRecords) {
        // 修改延迟操作意见
        BizApprovalRecord deferredRecord = new BizApprovalRecord();
        deferredRecord.setSequence(currApprovalRecords.get(0).getSequence());
        deferredRecord.setSerialNum(bizApprovalRecord.getSerialNum());
        deferredRecord.setDeferredRemark(bizApprovalRecord.getDeferredRemark());
        deferredRecord.setUpdateBy(loginUser.getUsername());
        deferredRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        bizApprovalRecordMapper.updateBizApprovalRecordBySerialNum(deferredRecord);
        iSyTableRecordTService.updateBusinessStatus(bizApprovalRecord.getSerialNum(),Constants.DEFERRED);
    }

    /**
     * 撤回
     *
     * @param bizApprovalRecord
     * @param loginUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult recallApprovalRecord(BizApprovalRecord bizApprovalRecord, LoginUser loginUser) {
        // 撤回
        AjaxResult recallResult = getRecallResult(bizApprovalRecord, loginUser);
        if (recallResult != null) {
            return recallResult;
        }
        //   修改申请人流程记录状态：已完成->撤回
        updateBizApprovalRecordBySerialNum(1, bizApprovalRecord.getSerialNum(), Constants.RECALL, loginUser.getUsername(), Constants.RECALL);
        //   修改当前流程记录状态：待审批->撤回
        updateBizApprovalRecordBySerialNum(2, bizApprovalRecord.getSerialNum(), Constants.RECALL, loginUser.getUsername(), null);
        iSyTableRecordTService.updateBusinessStatus(bizApprovalRecord.getSerialNum(),Constants.RECALL);
        return null;
    }

    /**
     * 驳回
     *
     * @param bizApprovalRecord
     * @param loginUser
     * @param currApprovalRecords
     */
    private void rejectedApprovalRecord(BizApprovalRecord bizApprovalRecord, LoginUser loginUser, List<BizApprovalRecord> currApprovalRecords) {
        // 操作驳回
        //    修改当前流程记录状态：审批中->驳回
        BizApprovalRecord approvalRecordParam = getBizApprovalRecord(bizApprovalRecord, loginUser, currApprovalRecords, Constants.REJECT, Constants.REJECTED);
        bizApprovalRecordMapper.updateBizApprovalRecordBySerialNum(approvalRecordParam);
        //   修改申请人流程记录状态：已完成->驳回
        updateBizApprovalRecordBySerialNum(1, bizApprovalRecord.getSerialNum(), Constants.REJECT, loginUser.getUsername(), Constants.REJECT);
        iSyTableRecordTService.updateBusinessStatus(bizApprovalRecord.getSerialNum(),Constants.REJECT);
    }

    /**
     * 同意
     *
     * @param bizApprovalRecord
     * @param loginUser
     * @param currApprovalRecords
     */
    @Transactional(rollbackFor = Exception.class)
    public void agreeApprovalRecord(BizApprovalRecord bizApprovalRecord, LoginUser loginUser, List<BizApprovalRecord> currApprovalRecords) {
        // 修改当前流程记录状态：审批中->已完成
        BizApprovalRecord approvalRecordParam = getBizApprovalRecord(bizApprovalRecord, loginUser, currApprovalRecords, Constants.COMPLETED, Constants.AGREE);
        bizApprovalRecordMapper.updateBizApprovalRecordBySerialNum(approvalRecordParam);

        // 获取该流水单号的所有审批记录
        List<BizApprovalRecord> allApprovalRecords = getBizApprovalRecords(bizApprovalRecord);
        // 判读是否追加审批人员
        if (!StringUtils.isBlank(bizApprovalRecord.getAppendApprovedUserIds())) {
            allApprovalRecords = addApprovalRecord(allApprovalRecords, bizApprovalRecord.getAppendApprovedUserIds(), loginUser);

        }
        // 该流水单号所有记录条数与当前记录序号对比，相等则审批为最后一个节点
        if (allApprovalRecords.size() != currApprovalRecords.get(0).getSequence()) {
            //    修改下一节点状态为审批中
            BizApprovalRecord nextNodeRecord = new BizApprovalRecord();
            nextNodeRecord.setApprovalStatus(Constants.APPROVE);
            Integer sequence = currApprovalRecords.get(0).getSequence() + 1;
            nextNodeRecord.setSequence(sequence);
            nextNodeRecord.setSerialNum(currApprovalRecords.get(0).getSerialNum());
            bizApprovalRecordMapper.updateBizApprovalRecordBySerialNum(nextNodeRecord);
            // 消息推送
            sendMessage(currApprovalRecords, allApprovalRecords, sequence);

        } else {
            //    修改业务表状态
            BizApprovalRecord approvalRecord = new BizApprovalRecord();
            approvalRecord.setBusinessStatus(Constants.COMPLETED);
            approvalRecord.setSerialNum(bizApprovalRecord.getSerialNum());
            approvalRecord.setSequence(1);
            bizApprovalRecordMapper.updateBizApprovalRecordBySerialNum(approvalRecord);
            iSyTableRecordTService.updateBusinessStatus(approvalRecord.getSerialNum(),Constants.COMPLETED);
            // 当最后一个审批人同意后，特殊处理
            treatSomething(bizApprovalRecord);
        }
    }

    /**
     * 审批完之后,特殊处理
     *
     * @param bizApprovalRecord
     */
    public void treatSomething(BizApprovalRecord bizApprovalRecord) {
        if (bizApprovalRecord.getSerialNum().indexOf("CGSQ") >= 0) {
            // 采购申请根据信息生成入库记录
            checkAndInsertApprovalRecord(bizApprovalRecord);
        }
        if (bizApprovalRecord.getSerialNum().indexOf("RZSQ") >= 0) {
            // 入职申请成功，新增员工信息，通讯记录
            iOaEntryService.addStaffInfo(bizApprovalRecord);
        }

    }

    /**
     * 撤回前校验
     *
     * @param bizApprovalRecord
     * @param loginUser
     * @return
     */
    private AjaxResult getRecallResult(BizApprovalRecord bizApprovalRecord, LoginUser loginUser) {
        // 获取该流水单号的所有审批记录
        List<BizApprovalRecord> allApprovalRecords = getBizApprovalRecords(bizApprovalRecord);
        for (BizApprovalRecord approvalRecord : allApprovalRecords) {
            if (approvalRecord.getSequence() == null) {
                return new AjaxResult(HttpStatus.ERROR, "审批单序号有误！");
            }
            // 判断当前操作是否是发起人
            if (approvalRecord.getSequence() == 1) {
                if (!loginUser.getUserId().equals(approvalRecord.getApproverId())) {
                    return new AjaxResult(HttpStatus.ERROR, "您不是发起人，不能撤回！");
                }
            }
            // 判断该审批单是否已审批，审批则不能撤回
            if (approvalRecord.getSequence() == 2) {
                if (!Constants.APPROVE.equals(approvalRecord.getApprovalStatus())) {
                    return new AjaxResult(HttpStatus.ERROR, "该审批单已被下一节点审批，请当前审批人驳回再提交。");
                }
            }
        }
        return null;
    }

    /**
     * 修改发起人状态
     *
     * @param sequence
     * @param serialNum
     * @param status
     * @param name
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBizApprovalRecordBySerialNum(Integer sequence, String serialNum, String status, String name, String businessStatus) {
        BizApprovalRecord record = new BizApprovalRecord();
        record.setSequence(sequence);
        record.setSerialNum(serialNum);
        record.setApprovalStatus(status);
        record.setBusinessStatus(businessStatus);
        record.setUpdateBy(name);
        record.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        bizApprovalRecordMapper.updateBizApprovalRecordBySerialNum(record);
    }

    /**
     * 获取所有审批记录
     *
     * @param bizApprovalRecord
     * @return
     */
    private List<BizApprovalRecord> getBizApprovalRecords(BizApprovalRecord bizApprovalRecord) {
        BizApprovalRecord allApprovalRecord;
        allApprovalRecord = new BizApprovalRecord();
        allApprovalRecord.setSerialNum(bizApprovalRecord.getSerialNum());
        List<BizApprovalRecord> allApprovalRecords = bizApprovalRecordMapper.selectBizApprovalRecordList(allApprovalRecord);
        return allApprovalRecords;
    }

    /**
     * 消息推送
     *
     * @param bizApprovalRecords
     * @param allApprovalRecords
     * @param sequence
     */
    private void sendMessage(List<BizApprovalRecord> bizApprovalRecords, List<BizApprovalRecord> allApprovalRecords, Integer sequence) {
        try {
            // 获取下一节点信息
            List<BizApprovalRecord> nextNodeList = allApprovalRecords.stream().filter(a -> a.getSequence().equals(sequence)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(nextNodeList)) {
                LOGGER.error("消息推送获取审批下一节点失败");
            }
            // 当前审批记录
            BizApprovalRecord currApprovalRecord = bizApprovalRecords.get(0);

            Message message = new Message();
            message.setFromId(currApprovalRecord.getApproverId());
            message.setFromName(currApprovalRecord.getApproverName());
            message.setStatus(currApprovalRecord.getApprovalStatus());
            message.setSerialNum(currApprovalRecord.getSerialNum());
            message.setType(currApprovalRecord.getSubscribePatternName());

            // 下一审批记录
            BizApprovalRecord nextApprovalRecord = nextNodeList.get(0);
            message.setNextNodeId(nextApprovalRecord.getApproverId());
            message.setNextNodeName(nextApprovalRecord.getApproverName());

            LOGGER.info("推送消息：" + JSON.toJSONString(message));
            webSocketServer.onMessage(JSON.toJSONString(message));

        } catch (Exception e) {
            LOGGER.error("操作审批之后消息推送失败", e);
        }
    }

    /**
     * 修改当前节点状态
     *
     * @param loginUser          当前登录人信息
     * @param bizApprovalRecords
     * @return
     */
    private static BizApprovalRecord getBizApprovalRecord(BizApprovalRecord BizApprovalRecord, LoginUser loginUser, List<BizApprovalRecord> bizApprovalRecords, String status, String typeOperation) {
        BizApprovalRecord approvalRecordParam = new BizApprovalRecord();
        approvalRecordParam.setApprovalStatus(status);
        approvalRecordParam.setTypeOperation(typeOperation);
        approvalRecordParam.setSequence(bizApprovalRecords.get(0).getSequence());
        approvalRecordParam.setSerialNum(bizApprovalRecords.get(0).getSerialNum());
        approvalRecordParam.setApprovalRemark(BizApprovalRecord.getApprovalRemark());
        approvalRecordParam.setRemark(BizApprovalRecord.getRemark());
        approvalRecordParam.setUpdateBy(loginUser.getUsername());
        approvalRecordParam.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecordParam;
    }

    /**
     * 采购申请根据信息生成入库记录
     *
     * @param bizApprovalRecord
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void checkAndInsertApprovalRecord(BizApprovalRecord bizApprovalRecord) {
        // 当最后一个审批人同意后，则采购申请根据信息生成入库记录
        try {
            // 根据流水单号判断是否为采购申请
            if (bizApprovalRecord.getSerialNum().indexOf("CGSQ") >= 0) {
                OaPurchase oaPurchase = new OaPurchase();
                oaPurchase.setSerialNum(bizApprovalRecord.getSerialNum());
                List<OaPurchase> oaPurchaseList = oaPurchaseMapper.selectOaPurchaseList(oaPurchase);
                if (!CollectionUtils.isEmpty(oaPurchaseList)) {
                    oaPurchase = oaPurchaseList.get(0);
                    List<BizReceiptProduct> bizReceiptProductList = new ArrayList<>();

                    OaPurchaseProduct oaPurchaseProduct = new OaPurchaseProduct();
                    oaPurchaseProduct.setPurchaseId(oaPurchase.getId());
                    List<OaPurchaseProduct> list = oaPurchaseProductMapper.selectOaPurchaseProductList(oaPurchaseProduct);

                    // 新增入库记录
                    BizReceipt bizReceipt = new BizReceipt();
                    bizReceipt.setReturnerId(oaPurchase.getUserId());
                    bizReceipt.setReturnerName(oaPurchase.getUsername());
                    bizReceipt.setCreateTime(DateUtils.getNowDate());
                    bizReceipt.setReturnType("2");// 入库类型为采购入库
                    bizReceipt.setStatus("1");// 采购入库申请通过状态
                    bizReceiptMapper.insertBizReceipt(bizReceipt);

                    // 新增入库产品记录
                    if (!CollectionUtils.isEmpty(list)) {
                        list.forEach(product -> {
                            BizReceiptProduct bizReceiptProduct = new BizReceiptProduct();
                            bizReceiptProduct.setProductId(product.getProductId());
                            bizReceiptProduct.setProductName(product.getProductName());
                            bizReceiptProduct.setModel(product.getModel());
                            bizReceiptProduct.setNumber(product.getNumber());
                            bizReceiptProduct.setPrice(product.getPrice());
                            bizReceiptProduct.setProductType(product.getProductType());
                            bizReceiptProduct.setReceiptId(bizReceipt.getId());
                            bizReceiptProductList.add(bizReceiptProduct);
                        });
                    }
                    if (!CollectionUtils.isEmpty(bizReceiptProductList)) {
                        bizReceiptProductList.forEach(product -> {
                            bizReceiptProductMapper.insertBizReceiptProduct(product);
                        });
                    }
                }
            }

        } catch (Exception e) {
            throw new RuntimeException("采购申请添加入库失败", e);
        }
    }

    /**
     * 批量删除审批信息记录
     *
     * @param ids 需要删除的审批信息记录主键
     * @return 结果
     */
    @Override
    public int deleteBizApprovalRecordByIds(Long[] ids) {
        return bizApprovalRecordMapper.deleteBizApprovalRecordByIds(ids);
    }

    /**
     * 删除审批信息记录信息
     *
     * @param id 审批信息记录主键
     * @return 结果
     */
    @Override
    public int deleteBizApprovalRecordById(Long id) {
        return bizApprovalRecordMapper.deleteBizApprovalRecordById(id);
    }

    /**
     * 查询处理过的审批记录
     *
     * @param bizApprovalRecord
     * @return
     */
    @Override
    public List<BizApprovalRecord> selectApprovalRecordProcessedList(BizApprovalRecord bizApprovalRecord) {
        return bizApprovalRecordMapper.selectApprovalRecordProcessedList(bizApprovalRecord);
    }

    /**
     * 默认模板 员工->部门主管->童总
     *
     * @param loginUser
     * @return
     */
    @Override
    public List<BizApprovalRecord> approvalTemplate(LoginUser loginUser, String serialNum,String type) {
        List<BizApprovalRecord> bizApprovalRecords = new ArrayList<>();
        int sequence = 1;
        // 员工
        BizApprovalRecord initiatorRecord = createApprovalRecord(loginUser, serialNum,type);
        initiatorRecord.setSequence(sequence);
        initiatorRecord.setApproverId(loginUser.getUserId());
        initiatorRecord.setApproverName(loginUser.getUsername());
        initiatorRecord.setApprovalStatus(Constants.COMPLETED);
        initiatorRecord.setTypeOperation(Constants.AGREE);
        initiatorRecord.setBusinessStatus(Constants.APPROVE);
        bizApprovalRecords.add(initiatorRecord);

        // 部门主管
        sequence++;
        SysDept dept = iSysDeptService.selectDeptById(loginUser.getDeptId());
        if (Objects.isNull(dept)) {
            throw new BaseException("部门信息为空");
        }
        if (StringUtils.isBlank(dept.getLeader())) {
            throw new BaseException("部门主管为空");
        }
        BizApprovalRecord deptApprovalRecord = createApprovalRecord(loginUser, serialNum,type);
        deptApprovalRecord.setSequence(sequence);
        deptApprovalRecord.setApproverId(dept.getLeaderId());
        deptApprovalRecord.setApproverName(dept.getLeader());
        deptApprovalRecord.setApprovalStatus(Constants.APPROVE);
        bizApprovalRecords.add(deptApprovalRecord);

        // 童总
        sequence++;
        BizApprovalRecord leaderApprovalRecord = createApprovalRecord(loginUser, serialNum,type);
        leaderApprovalRecord.setSequence(sequence);
        leaderApprovalRecord.setApproverId(3L);
        leaderApprovalRecord.setApproverName("童玲");
        leaderApprovalRecord.setApprovalStatus(Constants.NOT_APPROVED);
        bizApprovalRecords.add(leaderApprovalRecord);
        return bizApprovalRecords;
    }

    /**
     * 赋默认值
     *
     * @param loginUser
     * @param serialNum
     * @return
     */
    private BizApprovalRecord createApprovalRecord(LoginUser loginUser, String serialNum,String type) {
        BizApprovalRecord approvalRecord = new BizApprovalRecord();
        approvalRecord.setSubscribePatternName(type);
        approvalRecord.setSerialNum(serialNum);
        approvalRecord.setUserId(loginUser.getUserId());
        approvalRecord.setUsername(loginUser.getUsername());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(loginUser.getUsername());
        approvalRecord.setCreateBy(loginUser.getUsername());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 追加审批人
     *
     * @param list
     * @param appendApprovedName
     * @param loginUser
     */
    @Transactional(rollbackFor = Exception.class)
    public List<BizApprovalRecord> addApprovalRecord(List<BizApprovalRecord> list, String appendApprovedName, LoginUser loginUser) {
        List<BizApprovalRecord> bizApprovalRecords = new ArrayList<>();

        String[] approvers = appendApprovedName.split(",");
        List<Long> idList = Arrays.stream(approvers).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        // 获取详细审批人信息
        List<SysUser> sysUserList = sysUserMapper.selectUserByUserIds(idList);
        if (idList.size() != sysUserList.size()) {
            throw new BaseException("新增入职申请审批人有误");
        }
        // 根据职位级别降级排序
        sysUserList.sort(Comparator.comparingLong(SysUser::getPositionLevel).reversed());

        // 获取序号最大得审批记录
        BizApprovalRecord maxApprovalRecord = list.stream().max(Comparator.comparing(BizApprovalRecord::getSequence)).get();
        LOGGER.info(String.format("最大序号：%s", maxApprovalRecord.getSequence()));

        int sequence = maxApprovalRecord.getSequence();

        // 增加审批记录
        if (!CollectionUtils.isEmpty(sysUserList)) {
            for (int i = 0; i < sysUserList.size(); i++) {
                sequence++;
                BizApprovalRecord approvalRecord = new BizApprovalRecord();
                SysUser sysUser = sysUserMapper.selectUserById(sysUserList.get(i).getUserId());
                if (Objects.isNull(sysUser)) {
                    throw new BaseException("新增入职申请审批人信息有误");
                }
                BeanUtils.copyProperties(maxApprovalRecord, approvalRecord);
                approvalRecord.setApprovalStatus(Constants.APPROVE);
                approvalRecord.setApproverName(sysUser.getUserName());
                approvalRecord.setApproverId(sysUser.getUserId());
                approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
                approvalRecord.setUpdateBy(loginUser.getUsername());
                approvalRecord.setSequence(sequence);
                bizApprovalRecords.add(approvalRecord);
                list.add(approvalRecord);
            }
        }
        bizApprovalRecordMapper.insertBatchBizApprovalRecord(bizApprovalRecords);
        return list;
    }
}
